/*
 * @Author: 李无敌
 * @Date: 2025-07-30 11:15:21
 * @LastEditors: 李无敌
 * @LastEditTime: 2025-08-12 14:40:27
 * @FilePath: \nest-base\src\modules\auth\controllers\auth.controller.ts
 */
import { Controller, Post, Body, UseGuards, Request, Get } from '@nestjs/common';
import { ApiTags, ApiOperation, ApiBody, ApiResponse, ApiBearerAuth } from '@nestjs/swagger';
import { AuthGuard } from '@nestjs/passport';
import { SkipAuth } from '../../../common/decorators/roles.decorator';
// 修正 AuthService 的导入路径
import { AuthService } from '../services/auth.service';
// 修正 UserService 的导入路径
import { UserService } from '../../user/services/user.service';
import { LoginDto } from '../dto/login.dto';
import { AuthResponseDto } from '../dto/auth-response.dto';
import { ApiResponseDto } from '../../../common/dto/response.dto';
// 修正 User 实体的导入路径
import { User } from '../../user/entities/user.entity';
// 导入安全日志工具类
import { SecurityLogger } from '../../security-log/utils/security-logger.util';
import { ApiName } from '../../../common/decorators/api-name.decorator';
import { CurrentUser } from '../../../common/decorators/current-user.decorator';

@ApiTags('认证')
@ApiBearerAuth()
@Controller('auth')
export class AuthController {
  constructor(
    private readonly authService: AuthService,
    private readonly userService: UserService,
    private readonly securityLogger: SecurityLogger,
  ) {}

  @SkipAuth()
  @UseGuards(AuthGuard('local'))
  @Post('login')
  @ApiOperation({ summary: '用户登录' })
  @ApiName('用户登录')
  @ApiBody({ type: LoginDto })
  @ApiResponse({ status: 200, description: '登录成功', type: AuthResponseDto })
  @ApiResponse({ status: 401, description: '用户名或密码错误' })
  async login(@Request() req): Promise<ApiResponseDto<AuthResponseDto>> {
    const user = req.user as User;
    const ipAddress = this.getClientIP(req);
    const userAgent = req.headers['user-agent'];
    
    try {
      const authResponse = await this.authService.login(user, ipAddress, userAgent);
      
      // 记录登录成功事件
      await this.securityLogger.logAuthSuccess(
        user.id,
        user.username,
        ipAddress,
        userAgent,
        { loginTime: Date.now() }
      );
      
      return ApiResponseDto.success(authResponse, '登录成功');
    } catch (error) {
      // 记录登录失败事件
      await this.securityLogger.logAuthFailed(
        req.body?.username || 'unknown',
        ipAddress,
        error.message,
        userAgent,
        { loginTime: Date.now() }
      );
      throw error;
    }
  }

  @SkipAuth()
  @Post('logout')
  @ApiOperation({ summary: '用户登出' })
  @ApiName('用户登出')
  @ApiResponse({ status: 200, description: '登出成功' })
  async logout(@Request() req): Promise<ApiResponseDto<boolean>> {
    // 在JWT模式下，登出通常由前端删除令牌实现
    // 这里可以添加令牌黑名单逻辑
    return ApiResponseDto.success(true, '登出成功');
  }

  @Get('profile')
  @ApiOperation({ summary: '获取当前用户信息' })
  @ApiName('获取当前用户信息')
  async getProfile(@CurrentUser() user: User): Promise<ApiResponseDto<User>> {
    return ApiResponseDto.success(user, '获取用户信息成功');
  }

  private getClientIP(req: any): string {
    return (
      req.headers['x-forwarded-for'] ||
      req.headers['x-real-ip'] ||
      req.socket?.remoteAddress ||
      (req.socket?.socket?.remoteAddress 
        ? req.socket.socket.remoteAddress 
        : 'unknown')
    );
  }
} 